<!DOCTYPE html>
<html lang="zh">

	<head>
		<meta charset="UTF-8">
		<meta name="viewport"
			content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
		<meta http-equiv="X-UA-Compatible" content="ie=edge">
		<title style="font-size: 20px;">轨迹</title>

		<style type="text/css">
			html {
				height: 100%
			}

			body {
				height: 100%;
				margin: 0px;
				padding: 0px;
				overflow: hidden;
				background-color: #ddd;
			}

			#map {
				width: 100%;
				height: 100%;
			}

			#btns {
				display: flex;
				flex-direction: column;
				z-index: 99999999;
				position: absolute;
				bottom: 15%;
				right: 0%;
				width: 60px;
				overflow: hidden;
				align-items: center;
			}

			button {
				width: 46px;
				height: 46px;
				border-radius: 50%;
				outline: none;
				border: none;
				margin-bottom: 20px;
				background-color: #f1f1f1;
				color: #fff;
				z-index: 99999999;

			}

			#playTrackRecord {
				background-image: url("map/play_track.png");
				background-size: 60%;
				background-repeat: no-repeat;
				/* 防止背景图片重复 */
				background-position: 50%;
				border-radius: 50%;

			}



			/* .progress-bar {
				width: 0%;
				background-color: #ddd;
				position: relative;
				height: 16px;
				border-radius: 5px;
			}

			.progress {
				width: 0%;
				height: 100%;
				background-color: #4CAF50;
				border-radius: 8px;
				position: relative;
				bottom: 0;
				left: 0;
				height: 16px;
			} */

			.custom-range {
				-webkit-appearance: none;
				width: 90%;
				height: 16px;
				background: linear-gradient(to right, #1296db, #3185FC, #0047AB, #6495ED);
				outline: none;
				opacity: 0.7;
				-webkit-transition: .2s;
				transition: opacity .2s;
				border-radius: 9px;
			}

			.custom-range:hover {
				opacity: 1;
			}


			.custom-range::-webkit-slider-thumb {
				-webkit-appearance: none;
				/* 覆盖默认外观 */
				width: 26px;
				/* 滑块的宽度 */
				height: 26px;
				/* 滑块的高度 */
				background-image: url('map/navigation_track.png');
				/* 设置滑块的图片 */
				background-size: cover;
				/* 背景图片覆盖整个滑块 */
				border-radius: 50%;
				/* 滑块设置为圆形 */
			}

			.custom-range::-moz-range-thumb {
				width: 26px;
				/* 滑块的宽度 */
				height: 26px;
				/* 滑块的高度 */
				background-image: url('map/navigation_track.png');
				/* 设置滑块的图片 */
				background-size: cover;
				/* 背景图片覆盖整个滑块 */
				border-radius: 50%;
				/* 滑块设置为圆形 */
			}

			.custom-range::-ms-thumb {
				width: 26px;
				/* 滑块的宽度 */
				height: 26px;
				background-image: url("map/navigation_track.png");
				/* 设置滑块的图片 */
				background-size: cover;
				/* 背景图片覆盖整个滑块 */
				border-radius: 50%;
				/* 滑块设置为圆形 */
			}




			.bottom {
				background-color: #f1f1f1;
				border-top-left-radius: 20px;
				border-top-right-radius: 20px;
				/* 圆角 */
				margin: 0 10px;
				/* 左右边距20像素 */
				position: fixed;
				/* 固定位置 */
				bottom: 0;
				/* 底部对齐 */
				width: calc(100% - 20px);
				/* 宽度计算，‌确保左右边距后宽度仍然是全屏 */
				height: 0;
				text-align: center;
				/* 文本居中 */
				padding: 10px 0;
				/* 上下内边距，‌可以根据需要调整 */
				z-index: 999999;
				display: flex;
				align-items: center;
				justify-content: center;

			}

			#progress-bar-container {
				width: 80%;
				position: relative;
				background-color: #ddd;
				border-radius: 10px;
			}

			#progress-bar {
				width: 0%;
				height: 6px;
				background-color: #1296db;
				border-radius: 10px;
				transition: width 0.1s ease-in-out;
			}

			#progress-bar-playhead {
				position: absolute;
				top: 50%;
				left: 50%;
				height: 20px;
				width: 20px;
				border-radius: 50%;
				overflow: clip;
				transform: translateY(-50%);
				clip-path: circle(50% at 50% 50%);
				left: 0;
			}

			.gm-style iframe+div {
				border: none !important;
			}
		</style>
	</head>

	<body>
		<div id='map'></div>

		<!-- <div id="btns">
			<button id="playTrackRecord"> </button>
		</div> -->


		<div class="bottom" id="bottom">

			<!-- <div id="myProgress" class="progress" style="width:90%"></div> -->
			<!-- 	<input type="range" min="0" max="100" value="0" class="custom-range" id="myRange"
				onchange="setProgress(this.value)"> -->

			<div id="progress-bar-container">
				<div id="progress-bar" :style="{width:width}">
					<img src="map/navigation_track.png" id="progress-bar-playhead" />
				</div>
			</div>
		</div>

	</body>

	<script type="text/javascript" src="../uni.webview.1.5.2.js">
	</script>
	<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
	<script>
		(g => {
			var h, a, k, p = "The Google Maps JavaScript API",
				c = "google",
				l = "importLibrary",
				q = "__ib__",
				m = document,
				b = window;
			b = b[c] || (b[c] = {});
			var d = b.maps || (b.maps = {}),
				r = new Set,
				e = new URLSearchParams,
				u = () => h || (h = new Promise(async (f, n) => {
					await (a = m.createElement("script"));
					e.set("libraries", [...r] + "");
					for (k in g) e.set(k.replace(/[A-Z]/g, t => "_" + t[0].toLowerCase()), g[k]);
					e.set("callback", c + ".maps." + q);
					a.src = `https://maps.${c}apis.com/maps/api/js?` + e;
					d[q] = f;
					a.onerror = () => h = n(Error(p + " could not load."));
					a.nonce = m.querySelector("script[nonce]")?.nonce || "";
					m.head.append(a)
				}));
			d[l] ? console.warn(p + " only loads once. Ignoring:", g) : d[l] = (f, ...n) => r.add(f) && u().then(() => d[
				l](f, ...n))
		})({
			key: "AIzaSyCaJJDLbPygLYHFL1vi6AlcQmR1P1rRDvA",
			v: "weekly",
			// Use the 'v' parameter to indicate the version to use (weekly, beta, alpha, etc.).
			// Add other bootstrap parameters as needed, using camel case.
		});
	</script>
	<script type="text/javascript">
		// 获取url参数
		function getUrlParams(url) {
			const paramsRegex = /[?&]+([^=&]+)=([^&]*)/gi;
			const params = {};
			let match;
			while (match = paramsRegex.exec(url)) {
				params[match[1]] = match[2];
			}
			return params;
		}

		function getBottomHeightByPlatForm() {
			var userAgent = navigator.userAgent || navigator.vendor || window.opera;
			if (userAgent.match(/android/i)) {
				return 40;
			} else if (userAgent.match(/iPad|iPhone|iPod/i)) {
				return 30;
			} else {
				return 60;
			}
		}

		function setProgress(value) {
			console.log("value=====", value);
			// document.getElementById("myProgress").style.width = value + '%';
		}



		let intervalId;
		let bounds;
		var pathList = [];
		let map;
		let marker;
		let polyline;
		let path = [];
		let index = 0;
		let animationFrameId;
		let notPlay = true;
		let progressPercent;
		// 加载地图
		async function initMap() {
			const {
				Map
			} = await google.maps.importLibrary("maps");
			map = new Map(document.getElementById("map"), {
				zoom: 14,
				mapId: '9acf2d6299ded60c',//"4504f8b37365c3d0"
				mapTypeId: google.maps.MapTypeId.ROADMAP,
				zoomControl: false,
				mapTypeControl: false,
				fullscreenControl: false,
				scaleControl: false,
				clickableIcons: false,
				streetViewControl: false,
				center: path[0],
			});

			map.addListener('tilesloaded', function() {

			});

			const {
				AdvancedMarkerElement
			} = await google.maps.importLibrary("marker");

			const playFlagImg = document.createElement("img");
			playFlagImg.style.width = '24px'
			playFlagImg.style.height = '24px'
			playFlagImg.src = './map/navigation_track.png'
			marker = new google.maps.marker.AdvancedMarkerElement({
				map,
				position: path[0],
				content: playFlagImg,
			});

			// // 初始化标记
			// bounds = new google.maps.LatLngBounds();

		}

		function setDevicePosition(center) {
			map.setCenter(center);
			map.setZoom(14);
			marker.position = center;
		}


		function playTrackAnimation() {
			// 计算并调整视图以包含所有点

			if (progressPercent > 0 || path.length == 0) {
				return;
			}
			setMarkerAndPolyline();

			animatePath();
			// 播放开始时的起始时间点
			let startTime = Date.now();
			// / 设置定时器，每秒获取一次进度
			intervalId = setInterval(() => {
				// 当前时间点
				let currentTime = Date.now();
				// 播放时长，这里假设播放时长是固定的
				let duration = 500 * (path.length - 1); // 例如10秒
				// 已经播放的时间
				let elapsedTime = currentTime - startTime;
				// 播放进度，以毫秒为单位
				progressPercent = elapsedTime / duration * 100;
				if (progressPercent >= 100) progress = 100
				width = progressPercent + '%'
				iconWidth = (progressPercent - 3) + '%'
				document.getElementById('progress-bar').style.width = width;
				document.getElementById("progress-bar-playhead").style.left = iconWidth;
				if (progressPercent >= 100) {
					clearInterval(intervalId)
				}
			}, 30);
		}

		function animatePath() {
			// 如果轨迹回放结束，则停止动画

			if (index >= path.length - 1) {
				map.setZoom(13);
				cancelAnimationFrame(animationFrameId);
				return;
			}
			const start = path[index];
			const end = path[index + 1];
			const totalDuration = 1000; // 每段路径动画时长（毫秒）
			const startTime = performance.now(); // 获取当前时间戳
			
			function animateStep() {
				if (!polyline) {
					cancelAnimationFrame(animationFrameId);
					return;
				}
				const now = performance.now();
				const elapsedTime = now - startTime; // 计算经过的时间
				const progress = Math.min(elapsedTime / totalDuration, 1); // 进度（0到1）

				// 计算当前点的经纬度
				const lat = start.lat + (end.lat - start.lat) * progress;
				const lng = start.lng + (end.lng - start.lng) * progress;
				const currentPos = {
					lat,
					lng
				};
				if (polyline) {
					marker.position = currentPos;
					pathList.push(currentPos);
					polyline.setPath(pathList);
					marker.visible = true;
					map.panTo(currentPos);
					map.setCenter(currentPos);
				}

				// 平滑动画效果
				if (progress < 1) {
					animationFrameId = requestAnimationFrame(animateStep);
				} else {
					index++;
					// 动画完成一段后，继续下一段
					animatePath();
				}
			}
			animationFrameId = requestAnimationFrame(animateStep);
		}

		function playTrackRecordDot() {

			let interver = setInterval(() => {
				if (index >= path.length - 1) {
					map.setZoom(13);
					console.log("退出");
					clearInterval(interver);
					return;
				} else {
					createTrackMarker(path[index]);
					index++;
				}
			}, 1000);
		}

		function createTrackMarker(latLng) {
			map.setCenter(latLng);
			const playFlagImg = document.createElement("img");
			playFlagImg.style.width = '20px'
			playFlagImg.style.height = '20px'
			playFlagImg.src = 'map/navigation_track.png'
			const marker = new google.maps.marker.AdvancedMarkerElement({
				map,
				position: latLng,
				content: playFlagImg,
			});
		}


		function palyAnimatePathDot() {
			// 如果轨迹回放结束，则停止动画

			if (index >= path.length - 1) {
				map.setZoom(14);
				cancelAnimationFrame(animationFrameId);
				return;
			}

			const start = path[index];
			const end = path[index + 1];
			const totalDuration = 2000; // 每段路径动画时长（毫秒）
			const startTime = performance.now(); // 获取当前时间戳


			function animateStep() {

				const now = performance.now();
				const elapsedTime = now - startTime; // 计算经过的时间
				const progress = Math.min(elapsedTime / totalDuration, 1); // 进度（0到1）

				// 计算当前点的经纬度
				const lat = start.lat + (end.lat - start.lat) * progress;
				const lng = start.lng + (end.lng - start.lng) * progress;
				const currentPos = {
					lat,
					lng
				};
				map.setCenter(currentPos);
				const playFlagImg = document.createElement("img");
				playFlagImg.style.width = '20px'
				playFlagImg.style.height = '20px'
				playFlagImg.src = 'map/navigation_track.png'
				const marker = new google.maps.marker.AdvancedMarkerElement({
					map,
					position: currentPos,
					content: playFlagImg,
				});
				// 平滑动画效果
				if (progress < 1) {
					animationFrameId = requestAnimationFrame(animateStep);
				} else {
					index++;
					// 动画完成一段后，继续下一段
					palyAnimatePathDot();
				}
			}
			animationFrameId = requestAnimationFrame(animateStep);
		}



		//重置播放按钮
		function resetPlayBar() {
			width = 0 + '%'
			iconWidth = 0 + '%'
			progressPercent = 0;
			document.getElementById('progress-bar').style.width = width;
			document.getElementById("progress-bar-playhead").style.left = iconWidth;
			if (intervalId) {
				clearInterval(intervalId)
			}
		}

		function removePolyline() {
			if (polyline) {
				polyline.setMap(null);
				polyline.setPath([]);
				polyline = null;
			}
			path = [];
			pathList = [];
		}

		function setMarkerAndPolyline() {
			// path.forEach((element) => {
			// 	bounds.extend(element);
			// });
			// map.fitBounds(bounds);
			// 初始化折线对象
			polyline = new google.maps.Polyline({
				path: [], // 初始为空
				geodesic: true,
				strokeColor: '#1296db',
				strokeOpacity: 1.0,
				strokeWeight: 4,
				map: map
			});
			index = 0;
		}

		window.addEventListener('load', function() {
			// 页面包括图片、样式等外部资源全部加载完成后执行的代码
			// console.log('Page fully loaded, including all frames, objects and images');

		});


		window.addEventListener('UniAppJSBridgeReady', function() {

			uni.postMessage({
				data: {
					msg: "getTrackRecord",
				}
			})
			//接收处理app 发来的消息
			window.getVueMessage = (data) => {
				console.log('app发来的消息:', JSON.stringify(data));
				resetPlayBar();
				removePolyline();
				path = data;
				if (!map) {
					initMap();

				} else {
					if (path.length > 0) {
						document.getElementById('map').style.display = "block";
						setDevicePosition(path[0]);
					} else {
						document.getElementById('map').style.display = "none";
					}

				}
			}

			//设置底部高度
			document.getElementById('bottom').style.height = getBottomHeightByPlatForm() + 'px';


			document.getElementById('progress-bar-playhead').onclick = function() {
				playTrackAnimation();
			}
		});

		document.addEventListener('gesturestart', function(event) {
			event.preventDefault()
		})
	</script>